from django.db import migrations


def migrate(apps, schema_editor):
    Parameter = apps.get_model("api_app", "Parameter")
    PythonModule = apps.get_model("api_app", "PythonModule")
    IngestorConfig = apps.get_model("ingestors_manager", "IngestorConfig")
    PluginConfig = apps.get_model("api_app", "PluginConfig")

    ingestors = [
        "malware_bazaar.MalwareBazaar",
        "threatfox.ThreatFox",
    ]
    for ingestor in ingestors:
        module = PythonModule.objects.get(
            module=ingestor,
            base_path="api_app.ingestors_manager.ingestors",
        )
        p = Parameter.objects.create(
            name="limit",
            type="int",
            description="Max number of results.",
            is_secret=False,
            required=True,
            python_module=module,
        )
        p.full_clean()
        p.save()

        ic = IngestorConfig.objects.get(name=ingestor.split(".")[1])
        pc = PluginConfig(
            value=20,
            ingestor_config=ic,
            for_organization=False,
            owner=None,
            parameter=p,
        )
        pc.full_clean()
        pc.save()


def reverse_migrate(apps, schema_editor):
    Parameter = apps.get_model("api_app", "Parameter")
    PythonModule = apps.get_model("api_app", "PythonModule")
    IngestorConfig = apps.get_model("ingestors_manager", "IngestorConfig")
    PluginConfig = apps.get_model("api_app", "PluginConfig")

    ingestors = [
        "malware_bazaar.MalwareBazaar",
        "threatfox.ThreatFox",
    ]
    for ingestor in ingestors:
        module = PythonModule.objects.get(
            module=ingestor,
            base_path="api_app.ingestors_manager.ingestors",
        )
        ic = IngestorConfig.objects.get(name=ingestor.split(".")[1])
        p = Parameter.objects.get(
            name="limit",
            type="int",
            description="Max number of results.",
            is_secret=False,
            required=True,
            python_module=module,
        )
        PluginConfig.objects.get(
            parameter=p,
            ingestor_config=ic,
        ).delete()
        p.delete()


class Migration(migrations.Migration):
    atomic = False
    dependencies = [
        ("api_app", "0065_job_mpnodesearch"),
        ("ingestors_manager", "0026_alter_ingestor_config_malware_bazaar_threatfox"),
    ]

    operations = [migrations.RunPython(migrate, reverse_migrate)]
